package com.syl.servlet;

import com.syl.entity.User;
import com.syl.service.UserService;
import com.syl.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Classname UserCheckServlet
 * @Description
 * @Date 2025/8/2 9:45
 * @Created by SYL
 */

@WebServlet("/login/checkUser")
public class UserCheckServlet extends HttpServlet {

    UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        System.out.println("注册用户名username = " + username);

        User check = userService.check(username);

        // 设置响应类型为JSON
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();

        //
        // 返回JSON格式的结果
        if (check != null) {
            // 用户名已存在
            out.print("{\"exists\": true}");
        } else {
            // 用户名可用
            out.print("{\"exists\": false}");
        }
        out.flush();//用于强制将缓冲区中的数据立即写入到客户端
    }
}
